using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoroutineManager : Singleton<CoroutineManager>
{
    private Queue<IEnumerator> queue = new Queue<IEnumerator>();
    private IEnumerator current = null;
    private Coroutine currentCoroutine = null;
    private bool isFinish = true;

    private void FixedUpdate()
    {
        DoTask();
    }

    public void AddTask(IEnumerator enumerator)
    {
        queue.Enqueue(enumerator);
    }

    void DoTask()
    {
        if (queue.Count == 0 && current == null)
            return;

        if (current == null)
            current = queue.Dequeue();

        if (isFinish)
        {
            currentCoroutine = StartCoroutine(RunCurrent());
        }
    }

    private IEnumerator RunCurrent()
    {
        isFinish = false;
        yield return StartCoroutine(current);
        Finish();
    }

    public void Finish()
    {
        current = null;
        isFinish = true;
        currentCoroutine = null;
    }

    /// <summary>
    /// 立即中断当前协程并立刻执行新的协程
    /// </summary>
    public void ForceStart(IEnumerator newEnumerator)
    {
        // 1. 停止当前协程
        if (currentCoroutine != null)
        {
            StopCoroutine(currentCoroutine);
            currentCoroutine = null;
        }

        // 2. 清空当前任务状态
        current = null;
        isFinish = true;
        queue.Clear(); // 如果不希望清空队列，可以注释掉这一行

        // 3. 立即启动新协程
        current = newEnumerator;
        currentCoroutine = StartCoroutine(RunCurrent());
    }
}